export default {
  name: 'vForm',
  render(h) {
    let Form = {}
    Form.header = this.$slots.header || []
    Form.footer = this.$slots.default || []
    Form.body = Object.keys(this.form).map((key) => {
      let item = this.form[key]
      return item.protect ? null : (() => {
        return (
          <elCol span={this.col}>
            <vFormItem item={item} itemKey={key} />
          </elCol>
        )
      })()
    })
    return (
      <elForm ref="Form"
        model={this.form}
        labelWidth={this.labelWidth}
        nativeOnSubmit={this.onSubmit}
        labelPosition={this.labelPosition}>
        {[...Form.header, ...Form.body, ...Form.footer]}

      </elForm>
    )
  },
  props: {
    form: {
      required: true,
      type: Object
    },
    col: {
      type: Number,
      default: 2
    },
    reset: {
      type: Boolean,
      default: false
    },
    labelWidth: {
      type: String,
      default: '120px'
    },
    labelPosition: {
      type: String
    }
  },
  attached: function () { },
  mounted() {
    // this.resetForm()
  },
  methods: {
    onSubmit(e) {
      //
      this.$emit('submit', this.validate(), this.getForm())
      e.preventDefault()
    },
    validate() {
      return new Promise((resolve, reject) => {
        this.$refs.Form.validate((valid) => {
          valid ? resolve(true) : reject(false)
        })
      })
    },
    getForm() {
      let data = {}
      for (var key in this.form) {
        if (this.form.hasOwnProperty(key)) {
          data[key] = this.form[key].value
        }
      }
      return data
    },
    resetForm() {
      for (let prop in this.$refs.Form.model) {
        if (this.$refs.Form.model.hasOwnProperty(prop)) {
          if (this.form[prop].default instanceof Array) {
            this.form[prop].default.length = 0;
          }
          this.form[prop].value = this.form[prop].default || ''
          this.form[prop].hasOwnProperty('fileList') ? (this.form[prop].fileList = []) : ''
          // console.log('%c gc_this.form[prop]=>: ','color: MidnightBlue; background: Aquamarine; font-size: 20px;',this.form[prop]);
        }
      }
      setTimeout(() => {
        if (this.$refs.Form) { this.$refs.Form.resetFields() }
      }, 0)
    }
  },
  watch: {
    reset(is) {
      is ? this.resetForm() : ''
    }
  },
  beforeDestroy() {
    this.resetForm()
  }
}

